package com.zpark.it.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zpark.it.pojo.Admin;
import com.zpark.it.pojo.LoginForm;
import com.zpark.it.pojo.Student;
import com.zpark.it.pojo.Teacher;
import com.zpark.it.service.AdminService;
import com.zpark.it.service.StudentService;
import com.zpark.it.service.TeacherService;
import com.zpark.it.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.imageio.ImageIO;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Title: SystemController
 * @Author Charles
 * @Package com.zpark.it.controller
 * @Date 2023/7/29 21:20
 */
@Api(tags = "系统登录控制器")
@RestController
@RequestMapping("/sms/system")
public class SystemController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;


    @GetMapping("getInfo")
    public Result getInfoByToken(@RequestHeader("token") String token){//获取请求头
        //校验token是否过期
        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration) {
            return Result.build(null, ResultCodeEnum.TOKEN_ERROR);
        }
        //从token中解析出用户id和用户类型
        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);

        Map<String,Object> map=new LinkedHashMap<>();
        switch (userType){
            case 1:
                Admin admin=adminService.getAdminById(userId);
                map.put("userType",1);
                map.put("user",admin);
                break;
            case 2:
                Student student=studentService.getStudentById(userId);
                map.put("userType",2);
                map.put("user",student);
                break;
            case 3:
                Teacher teacher=teacherService.getByTeacherById(userId);
                map.put("userType",3);
                map.put("user",teacher);
                break;
        }

        return Result.ok(map);
    }



    /**
     * 登录方法
     * @param loginForm
     * @param request
     * @return
     */

    @PostMapping("login")
    public Result login(@RequestBody LoginForm loginForm,HttpServletRequest request){
        //1、验证码是否正确
        HttpSession session = request.getSession();

        String sessionVerifiCode = (String)session.getAttribute("verifiCode");
        System.out.println("验证码"+sessionVerifiCode);

        String loginVerifiCode = loginForm.getVerifiCode();
        System.out.println("登录的验证码："+loginVerifiCode);
        //判断session验证码是否为空
        if("".equals(sessionVerifiCode)||sessionVerifiCode==null){
            return Result.fail().message("session中验证码已经过期，或者为空");
        }
        if (!sessionVerifiCode.equals(loginVerifiCode)) {
            return Result.fail().message("验证码错误");
        }

        //先从session中移除此次验证码
        session.removeAttribute("verifiCode");
        //2、用户类型进行检验
        Map<String,Object> map=new LinkedHashMap<>();
        switch (loginForm.getUserType()){
            case 1:
                try {
                    Admin admin=adminService.login(loginForm);
                    if (null!=admin) {
                        //用户的类型和用户id转为一个密文，以token的名称向客户端反馈
                        map.put("token", JwtHelper.createToken(admin.getId().longValue(),1));
                    }else {
                        throw new RuntimeException("用户名或者密码错误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
            case 2:
                try {
                    Student student=studentService.login(loginForm);
                    if (null!=student) {
                        //用户的类型和用户id转为一个密文，以token的名称向客户端反馈
                        map.put("token", JwtHelper.createToken(student.getId().longValue(),2));
                    }else {
                        throw new RuntimeException("用户名或者密码错误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }

            case 3:
                try {
                    Teacher teacher=teacherService.login(loginForm);
                    if (null!=teacher) {
                        //用户的类型和用户id转为一个密文，以token的名称向客户端反馈
                        map.put("token", JwtHelper.createToken(teacher.getId().longValue(),3));
                    }else {
                        throw new RuntimeException("用户名或者密码错误");
                    }
                    return Result.ok(map);
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
        }

        return Result.fail().message("没有该用户");

    }



    /**
     * 获取验证码
     * @param request
     * @param response
     */
    @GetMapping ("/getVerifiCodeImage")
    public void getVerifiCodeImage(HttpServletRequest request, HttpServletResponse response){
        //获取图片
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();

        //获取图片的验证码
        String verifiCode = new String(CreateVerifiCodeImage.getVerifiCode());

        //将验证码文本放入session域,为下一次验证做准备
        HttpSession session = request.getSession();
        session.setAttribute("verifiCode",verifiCode);
        //将验证码响应给浏览器
        try {
            ImageIO.write(verifiCodeImage,"JPEG",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation("文件上传统一入口")
    @PostMapping("headerImgUpload")
    public Result headerImgUpload(@ApiParam("这是要上传的头像文件") @RequestPart("multipartFile") MultipartFile multipartFile,
    HttpServletRequest request){
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        String originalFilename = multipartFile.getOriginalFilename();//原来图片的名字
        //找到原来图片名字的最后出现的.索引
        int i = originalFilename.lastIndexOf(".");
        //得到新的文件名
        String newFileName=uuid+originalFilename.substring(i);  //从.开始向后截取

        //保存图片文件 将文件发送到第三方/独立的图片服务器上
        String portraitPath="E:/Desktop/myzhxy/target/classes/public/upload".concat(newFileName);
        try {
            multipartFile.transferTo(new File(portraitPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //响应图片路径
        String path="upload/"+newFileName;
        return Result.ok(path);
    }


    @ApiOperation("更新用户密码的处理器")
    @PostMapping("/updatePwd/{oldPwd}/{newPwd}")
    public Result updatePwd(@RequestHeader("token") String token,
                            @PathVariable String oldPwd,
                            @PathVariable String newPwd){

        //检查token是否过期
        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration) { //token过期
            return Result.fail().message("token过期，请重新登录后修改密码");
        }
        //获取用户id和用户类型
        Integer userType = JwtHelper.getUserType(token);
        Long userId = JwtHelper.getUserId(token);
        oldPwd= MD5.encrypt(oldPwd);
        newPwd=MD5.encrypt(newPwd);
        switch (userType){
            case 1:
                QueryWrapper<Admin> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("id",userId.intValue());
                queryWrapper.eq("password",oldPwd);
                Admin admin = adminService.getOne(queryWrapper);
                if (admin!=null){
                    //修改密码
                    admin.setPassword(newPwd);
                    adminService.saveOrUpdate(admin);
                }else {
                    return Result.fail().message("原密码有误");
                }
                break;

            case 2:
                QueryWrapper<Student> queryWrapper2=new QueryWrapper<>();
                queryWrapper2.eq("id",userId.intValue());
                queryWrapper2.eq("password",oldPwd);
                Student student = studentService.getOne(queryWrapper2);
                if (student!=null){
                    //修改密码
                    student.setPassword(newPwd);
                    studentService.saveOrUpdate(student);
                }else {
                    return Result.fail().message("原密码有误");
                }
                break;

            case 3:
                QueryWrapper<Teacher> queryWrapper3=new QueryWrapper<>();
                queryWrapper3.eq("id",userId.intValue());
                queryWrapper3.eq("password",oldPwd);
                Teacher teacher = teacherService.getOne(queryWrapper3);
                if (teacher!=null){
                    //修改密码
                    teacher.setPassword(newPwd);
                    teacherService.saveOrUpdate(teacher);
                }else {
                    return Result.fail().message("原密码有误");
                }
                break;
        }
        return Result.ok();
    }

}
